import type { CSSProperties } from 'react';
import React from 'react';

import styles from './index.module.scss';

export interface DesProps {
  children: React.ReactNode;
  labelWidth?: CSSProperties['width'];
}

export interface DesItemProps {
  label: React.ReactNode;
  value: React.ReactNode;
  labelWidth?: CSSProperties['width'];
}

function Des({ children, labelWidth }: DesProps) {
  return (
    <div className={styles['des']}>
      {React.Children.map(children, (child) => {
        if (!React.isValidElement(child)) {
          return child;
        }

        if (child.type === Des.Item) {
          return React.cloneElement(child, {
            labelWidth
          } as Partial<DesItemProps>);
        }

        return child;
      })}
    </div>
  );
}

function Item({ label, value, labelWidth }: DesItemProps) {
  return (
    <div className={styles['des-item']}>
      <span
        className={styles['des-item-label']}
        style={{
          width: labelWidth
        }}
      >
        {label}
      </span>
      <span
        className={styles['des-item-value']}
        style={{
          marginLeft: labelWidth
        }}
      >
        {value}
      </span>
    </div>
  );
}

Des.Item = Item;

export default Des;
